package edu.cug.water.crawler.job.task.ministerial;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.cug.water.crawler.common.annotation.BeanField;
import edu.cug.water.crawler.common.constant.Constant;
import edu.cug.water.crawler.common.constant.EsConstants;
import edu.cug.water.crawler.common.exception.RRException;
import edu.cug.water.crawler.common.utils.DateUtils;
import edu.cug.water.crawler.common.utils.EsUtils;
import edu.cug.water.crawler.job.entity.ministerial.ImportantOfNationalWaterAndRainInformation;
import edu.cug.water.crawler.job.request.RequestUtil;
import edu.cug.water.crawler.job.task.ITask;
import edu.cug.water.crawler.job.utils.AbstractCrawlerTask;
import edu.cug.water.crawler.job.utils.DataConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component("job:ImportantOfNationalWaterAndRainInformation")
@Slf4j
public class ImportantOfNationalWaterAndRainInformationTask extends AbstractCrawlerTask<ImportantOfNationalWaterAndRainInformation> implements ITask {

    @Autowired
    private EsUtils esUtils;

    @Autowired
    private RequestUtil requestUtil;

    @Override
    public int run(String params) throws IOException {

        init();

        ResponseEntity<String> response = getRequestBody();

        List<ImportantOfNationalWaterAndRainInformation> list = getDataFromStr(response.getBody());
        log.info("{} converts results：{}", getClass().getName(), list.size());

        String s = esUtils.addDocuments(EsConstants.TypeConstant.IMPORTANT_OF_NATIONAL_WATER_AND_RAIN_INFORMATION.getValue(), list);

        Boolean aBoolean = esUtils.statusJudge(s);

        if (!aBoolean) throw new RRException(getClass().getName() + Constant.LogConstants.THE_PROCESS_OF_ES_STORE_FAILED.getValue());

        return list.size();
    }

    @Override
    protected void init() {
        super.init();
        url = "http://xxfb.mwr.cn/hydroSearch/pointHydroInfo";
        headers.set("Host", "xxfb.mwr.cn");
        headers.set("Connection", "keep-alive");
        headers.set("Accept", "application/json, text/javascript, */*; q=0.01");
        headers.set("X-Requested-With", "XMLHttpRequest");
        headers.set("Content-Type", "application/json");
        headers.set("Referer", "http://xxfb.mwr.cn/sq_zdysq.html");
        headers.set("Accept-Encoding", "gzip, deflate");
        headers.set("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
        headers.set("Cookie", "__FT10000066=2021-7-2-21-1-50; __NRU10000066=1625230910440; __REC10000066=4; __RT10000066=2021-8-16-20-50-10; zhuzhan=97700904");
    }

    @Override
    public ResponseEntity<String> getRequestBody() {
        return requestUtil.get(url, headers);
    }

    @Override
    public List<ImportantOfNationalWaterAndRainInformation> getDataFromStr(String body) {
        if (StringUtils.isEmpty(body))
            throw new RRException(getClass().getName() + Constant.LogConstants.RESPONSE_IS_NULL.getValue());

        List<ImportantOfNationalWaterAndRainInformation> results = new ArrayList<>();

        JSONObject response = (JSONObject)JSONObject.parse(body);

        log.info("response data: message {}", response.get("message"));

        JSONObject result = response.getJSONObject("result");
        JSONArray data = result.getJSONArray("data");

        for (Object item : data) {
            JSONObject temp = (JSONObject) item;

            ImportantOfNationalWaterAndRainInformation entity = new ImportantOfNationalWaterAndRainInformation();
            Field[] fields = entity.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.getAnnotation(BeanField.class) == null) continue;
                String property = field.getAnnotation(BeanField.class).property();
                field.setAccessible(true);
                try {
                    if ("stationCode".equals(field.getName())) field.set(entity, DataConvertUtil.stationCodeConvert(temp.get(property) + ""));
                    else field.set(entity, (temp.get(property) + "").trim());
                } catch (IllegalAccessException e) {
                    log.error("ImportantOfNationalWaterAndRainInformation Task parse 出错！");
                    throw new RRException(getClass().getName() + Constant.LogConstants.FIELD_ASSIGNMENT_ILLEGAL_ACCESS.getValue());
                }
            }
            entity.setCreatTime(DateUtils.formatDateTime(new Date()));
            results.add(entity);
        }
        return results;
    }
}
